import axios from 'axios'
import config from '../config';

// 判断当前URL所处环境,environment(env)
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

// 工具类，获得传入信息
class HttpRequest {
    constructor(baseUrl){
        this.baseUrl = baseUrl;
    }
    // 定义axios的相关配置
    getInsideConfig(){
        const config = {
            baseUrl:this.baseUrl,
            header:{}
        }
        return config
    }
    // inerceptors拦截器
    interceptors(instance){
        // Add a request interceptor
        instance.interceptors.request.use(function (config) {
            // Do something before request is sent
            return config;
        }, 
        function (error) {
            // 请求失败处理
            return Promise.reject(error);
        });

        // Add a response interceptor
        instance.interceptors.response.use(function (response) {
            // Do something with response data
            console.log(response,'response')
            return response;
        }, 
        function (error) {
            // 响应失败处理
            console.log(error,'error')
            return Promise.reject(error);
        });
    }
    //接收axios的相关配置
    request(options){
        //创建axios实例instance
        const instance = axios.create()
        options = {
            //获得axios的相关配置信息和传入参数并解构
            ...this.getInsideConfig() , ...options
        }
        //调用拦截器
        this.interceptors(instance)
        return instance(options)
    }
}

export default new HttpRequest(baseUrl)